package com.wlyuan.open.scanner.application.handler.table;

import com.alibaba.fastjson.JSON;
import com.wlyuan.open.scanner.application.annotation.TableScannerName;
import com.wlyuan.open.scanner.constant.TableEnum;
import com.wlyuan.open.scanner.repository.WayBillRepository;
import com.wlyuan.open.scanner.utils.enums.order.OrderStatusEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author lijing
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
@TableScannerName(isDefault = false, tableName = TableEnum.ORDER)
public class OrderTableToIncrHandler extends BaseTableToIncrHandler {
    private final WayBillRepository wayBillRepository;
    private static final String INDEX_SRC_CLASS = "Index_SrcClass";
    private static final String INDEX_STATUS = "Index_Status";
    private static final String INDEX_ID = "Index_ID";
    private static final String INDEX_CREATE_COMPANY_ID = "Index_CreatorCompanyID";
    private static final String INDEX_SRC_ORDER_ID = "Index_SrcOrderID";

    @Override
    public List<String> handler(String tableName, String data, String beforeData) {

        var businessParams = params(data, beforeData);

        if (StringUtils.isBlank(businessParams)) {
            logger.error("{}表业务分流参数不能为空", tableName);
            return Collections.emptyList();
        }
        var srcClass = Long.valueOf(businessParams);
        return buildOrderName(srcClass);
    }

    private String params(String data, String beforeData) {
        var map = JSON.parseObject(data, Map.class);
        //businessParams 为 srcClass
        var businessParams = String.valueOf(map.get(INDEX_SRC_CLASS));
        logger.info("order_index srcClass params : {}", businessParams);
        //草稿 和 新单据 不同步
        var status = Integer.valueOf(String.valueOf(map.get(INDEX_STATUS)));
        if (OrderStatusEnum.isSync(status)) {
            logger.info("状态为草稿 或 新单据 不同步：{}", status);
            return "";
        }
        saveUpDownStream(map, beforeData);
        return businessParams;
    }

    private void saveUpDownStream(Map<String, Object> map, String beforeData) {
        //新增
        if (StringUtils.isBlank(beforeData)) {
            wayBillRepository.save(Long.valueOf(String.valueOf(map.get(INDEX_ID))),
                    Long.valueOf(String.valueOf(map.get(INDEX_CREATE_COMPANY_ID))),
                    Long.valueOf(String.valueOf(map.get(INDEX_SRC_ORDER_ID))),
                    Long.valueOf(String.valueOf(map.get(INDEX_SRC_CLASS)))
            );
        }

    }

}
